package com.authine.cloudpivot.ext.controller.fileInfo.com;

import com.authine.cloudpivot.engine.api.model.bizmodel.BizPropertyModel;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Author hxd
 * @Date 2022/12/6 17:03
 * @Description
 **/

@RestController
@RequestMapping("/public/companyArchive")
@Slf4j
public class CompanyArchiveController extends BaseController {

    @Autowired
    CloudSqlService sqlService;

    /**
     *  获取总公司档案列表数据
     * @param page
     * @param size
     * @return
     */
    @RequestMapping("getFileInfoBaeList")
    public List getFileInfoBaeList(Integer page,Integer size){

        String schemaCode = "fileInfoBase";

        String tableName = getBizObjectFacade().getTableName(schemaCode);

        List<BizPropertyModel> list = getBizPropertyFacade().getListBySchemaCode(schemaCode,true);

        String codes = list.stream().filter(a-> !a.getDefaultProperty()).map(a -> a.getCode()).collect(Collectors.joining(","));

        StringBuilder sql = new StringBuilder("SELECT ").append(codes).append("  from ")
                .append(tableName);

        if (page != null &&  size != null) {
            if (page>0){
                page = (page-1)*size;
            }
            String limit = String.format(" limit %d,%d", page, size);
            sql.append(limit);
        }
        List<Map<String, Object>> mapList = sqlService.getList(sql.toString());

        return mapList;
    }



    /**
     *  公司级档案基础信息 新增 审批流完成后 数据写到基础表-公司级档案
     */
    @Async
    @RequestMapping("addFileInfoBase")
    public void addFileInfoBase(String bizId){
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.companyFileBaseAdd, bizId);

//        Object pushAllResult = bizObject.get("pushAllResult");


        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get("sheetCompanyFile");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));


        //获取审批人
        String approvalType = (String) list.get(0).get("approvalType");
        String approval = getFileBaseInfoWorkFlowApproval(bizObject, approvalType);


        for (Map<String, Object> map : list) {
            String fileCode = (String) map.get("fileCode");

            try {

                //调用存储过程
                callProcess(map, approval);

            } catch (Exception e) {
                log.info("基础表-公司档案  添加失败 fileCode={}", fileCode);
                log.info(e.getMessage(), e);
            }

        }
    }
    /**
     *  公司级档案基础信息 作废 审批流完成后 数据写到基础表-公司级档案
     */
    @Async
    @RequestMapping("toVoid")
    public void toVoid(String bizId){
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.companyFileBaseInfoVoid, bizId);

//        Object pushAllResult = bizObject.get("pushAllResult");


        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get("sheetCompanyFileVoid");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));


        //获取审批人
        String approvalType = (String) list.get(0).get("approvalType");
        String approval = getFileBaseInfoWorkFlowApproval(bizObject, approvalType);


        for (Map<String, Object> map : list) {
            String fileCode = (String) map.get("fileCode");

            try {

                //调用存储过程
                callProcessToVoid(map, approval);

            } catch (Exception e) {
                log.info("基础表-公司档案  添加失败 fileCode={}", fileCode);
                log.info(e.getMessage(), e);
            }

        }
    }
    /**
     *  调用存储过程
     -----公司级档案基础信息			----2023.03.22
     exec     SyncComArchiveInfo
     @comCode			nvarchar(100),			----公司代码
     @archtypeCode		nvarchar(100),			----档案类型代码   CA   DS-F
     @basecode		nvarchar(100),			----基础代码
     @basefid		nvarchar(100),			----基础FID
     @basedesc		nvarchar(100),			----对应说明
     @manfuncode		nvarchar(100),			----管理职能代码
     @ManDeptCode		nvarchar(100),			----管理部门代码
     @PosACode		nvarchar(100),			----岗A代码
     @PosBCode		nvarchar(100),			----岗B代码
     @Serial			nvarchar(100),			----序号
     @Number			nvarchar(100),			----档案代码
     @Name			nvarchar(200),			----档案名称
     @Remark			nvarchar(100),			----备注
     @Desc			nvarchar(500),			----说明
     @elec			nvarchar(20),			----电子版    1 √   0  ×   2 /
     @funcode		nvarchar(100),			----职能代码
     @MainDeptCode		nvarchar(100),			----主责部门代码
     @MainPosCode		nvarchar(100),			----主责岗代码
     @mainperson		nvarchar(100),			----主责人
     @auditor		nvarchar(100)			----02.0100 张三
     */
    private void callProcess(Map<String, Object> map, String approval){

        if (ObjectUtils.isEmpty(map)) {
            return;
        }

        log.info("入参map={}", map);

        //调用存储过程
        String maincom = MapUtils.getString(map, "companyCode", "");//公司代码
        String archTypeCode = MapUtils.getString(map, "archTypeCode", "");//档案类型代码   CA   DS-F
        String baseCode = MapUtils.getString(map, "baseCode", "");//基础代码
        String basicCodeFid = MapUtils.getString(map, "relevBaseCode", "");//基础代码fid
        String BaseFID = MapUtils.getString(map, "relevBaseCode", "");//基础代码FID

        String dysm = MapUtils.getString(map, "refDes", "");//对应说明
        String manageFun = MapUtils.getString(map, "manageFun", "");//管理职能代码
        String manageDept = MapUtils.getString(map, "manageDept", "");//管理部门代码
        String postionACode = MapUtils.getString(map, "postionACode", "");//岗A代码
        String postionBCode = MapUtils.getString(map, "postionBCode", "");//岗B代码
        String serialNo = MapUtils.getString(map, "serialNo", "");//序号
        String fileCode = MapUtils.getString(map, "fileCode", "");//档案代码
        String fileName = MapUtils.getString(map, "fileName", "");//档案名称
        String remarks = MapUtils.getString(map, "remarks", "");//备注
        String des = MapUtils.getString(map, "des", "");//说明
        String elec = MapUtils.getString(map, "elec", "");//电子版      1   √     0    x     2  /
        String auth = "";
        if ("√".equals(elec)) {
            elec = "1";
            auth = "1";
        } else if ("×".equals(elec)) {
            elec = "0";
            auth = "3";
        } else {
            elec = "2";
            auth = "3";
        }
        String funNumber = MapUtils.getString(map, "znCode", "");//职能代码
        String mainDeptNumber = MapUtils.getString(map, "defaultmainDeptId", "");//主责部门代码
        String mainPositionCode = MapUtils.getString(map, "mainPositionCode", "");//主责岗代码

        String mainUser = MapUtils.getString(map, "mainUser", "");//主责人
        String auditDate = DateFormatUtils.format(new Date(), "yyyy-MM-dd");//审批时间


        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncComArchiveInfo '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                maincom, archTypeCode, baseCode, basicCodeFid,dysm,
                manageFun, manageDept, postionACode, postionBCode, serialNo,
                fileCode,fileName, remarks, des, elec,
                funNumber, mainDeptNumber, mainPositionCode, mainUser,
                approval);

        log.info("\n==========准备调用存储过程:{}", execSql);

        sqlService.execute(CloudSqlService.htEas, execSql);

        log.info("\n=============存储过程执行完成");

    }

    /**
     ------公司级档案作废			----2023.03.22
     exec    ComArchiveDisable
     @ComCode	nvarchar(100),		-----公司代码
     @code     	nvarchar(100)		-----档案代码
     */
    private void callProcessToVoid(Map<String, Object> map, String approval) {

        if (ObjectUtils.isEmpty(map)) {
            return;
        }

        log.info("入参map={}", map);

        //调用存储过程
        String companyCode = MapUtils.getString(map, "companyCode", "");//公司代码
        String fileCode = MapUtils.getString(map, "fileCode", "");//档案代码



        String execSql = String.format("exec [HG_LINK].[hg].[dbo].ComArchiveDisable '%s','%s'",
                companyCode, fileCode);

        log.info("\n==========准备调用存储过程:{}", execSql);

        sqlService.execute(CloudSqlService.htEas, execSql);

        log.info("\n=============存储过程执行完成");

    }

    /**
     *  查询审批人,返回  员工号+姓名
     * @param bizObject
     * @param approvalType
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject, String approvalType) {
        String mainDeptCode = (String) bizObject.get("mainDeptCode");
        String activityCode ="";
        if ("0".equals(approvalType)){
            String manageDeptCode = (String) bizObject.get("manageDeptCode");
            if (mainDeptCode.equals(manageDeptCode)){
                activityCode="Activity11";
            }else{
                activityCode="Activity13";

            }
        }else if("1".equals(approvalType)) {
            String frameDeptCode = (String) bizObject.get("frameDeptCode");
            if (mainDeptCode.equals(frameDeptCode)){
                activityCode="Activity16";
            }else{
                activityCode="Activity20";
            }
        }


        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        final String finalActivityCode = activityCode;
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }

        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }

        UserModel user = getOrganizationFacade().getUser(participant);


        return new StringBuilder(user.getEmployeeNo()).append(user.getName()).toString();
    }



    /**
     * 判断是否已存在
     * @param field
     * @param value
     * @param schemaCode
     * @return
     */
    private String existsBizObject(String field,String value,String schemaCode){

        String tableName = getBizObjectFacade().getTableName(schemaCode);

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where ").append(field).append("='").append(value).append("'");

        Map<String, Object> map = sqlService.getMap(sql.toString());

        return (String) map.get("id");
    }

    /**
     *  转换成  基础表-总公司档案 的数据
     * @param map
     * @param auditDate
     * @return
     */
    private Map<String,Object> fileInfoBaseMap(Map<String,Object> map,String auditDate,String auditer){
        Map<String, Object> data = new HashMap<>();


        //档案代码
        data.put("fileCode",map.get("fileCode"));
        //档案名称
        data.put("fileName",map.get("fileName"));
        //主责关联公司
        data.put("mainComGuanlian",map.get("maincom"));
        //主责公司代码
        data.put("mainCompanyCode",map.get("mainComYingshe"));
        //主责公司名称
        data.put("mainCompanyName",map.get("maincomName"));
        //档案类型关联
        data.put("relevFileType",map.get("typeName"));
        //档案类型
        data.put("fileType",map.get("archTypeNumber"));
        //对应记录
        data.put("dyjl",map.get("record"));
        //关联基础代码
        data.put("relevBaseCode",map.get("relevBaseCode"));
        //基础代码
        data.put("baseCode",map.get("baseCode"));
        //基础名称
        data.put("baseCodeName",map.get("name01"));
        //对应说明
        data.put("refDesc",map.get("refDes"));
        //管理职能
        data.put("manageFun",map.get("manageFun"));

        //关联管理部门
        data.put("manageFun",map.get("relevManageDept"));
        //管理部门代码
        data.put("manageDeptCode",map.get("manageDept"));
        //管理部门
        data.put("manageDeptName",map.get("manageDeptName"));
        //关联岗A
        data.put("relevPosA",map.get("relevPositionA"));
        //岗A代码
        data.put("posA",map.get("postionACode"));
        //岗A
        data.put("posAName",map.get("positionAName"));
        //关联岗B
        data.put("relevPosB",map.get("relevPositionB"));
        //岗B代码
        data.put("posB",map.get("postionBCode"));
        //岗B
        data.put("posBName",map.get("positionBName"));

        //备注
        data.put("remark",map.get("remarks"));
        //电子版
        data.put("elec",map.get("elec"));
        //说明
        data.put("explains",map.get("des"));
        //职能关联
        data.put("fun",map.get("zn"));
        //职能代码
        data.put("funCode",map.get("znCode"));
        //职能
        data.put("funName",map.get("znName"));

        //主责部门关联
        data.put("relevMainDept",map.get("MainDeptId"));
        //主责部门代码
        data.put("mainDeptCode",map.get("defaultmainDeptId"));
        //主责部门
        data.put("dept",map.get("MainDept"));
        //主责岗关联
        data.put("relevMainPosition",map.get("mainPositionId"));
        //主责岗代码
        data.put("mainPositionCode",map.get("mainPositionCode"));
        //主责岗
        data.put("mainPosition",map.get("mainPostionName"));

        //公司授权信息
        data.put("mainCompanyAuthInfo",map.get("purview"));
        //纸质数量
//        data.put("paperNum",map.get(""));
        //01授权
//        data.put("one",map.get("1"));
        //02授权
//        data.put("two",map.get("1"));
        //03授权
//        data.put("three",map.get("1"));
        //04授权
//        data.put("four",map.get("1"));
        //05授权
//        data.put("five",map.get("1"));
        //06授权
//        data.put("six",map.get("1"));
        //07授权
//        data.put("seven",map.get("1"));
        //08授权
//        data.put("eight",map.get("1"));
        //09授权
//        data.put("nine",map.get("1"));
        //10授权
//        data.put("ten",map.get("1"));
        //工作说明
        data.put("jobDesc",map.get("refDes"));
        //审批时间
        data.put("auditDate",auditDate);
        //审批人
        data.put("auditer",auditer);

        //序号
        data.put("serialNo",map.get("serialNo"));

        //主责人
        data.put("mainUser",map.get("mainUser"));

        return data;
    }


}
